package com.earogya.logic.medical_records;

import java.io.IOException;
import java.util.ArrayList;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.v251.message.ACK;
import ca.uhn.hl7v2.model.v251.message.ADR_A19;
import ca.uhn.hl7v2.model.v251.message.QRY_A19;
import ca.uhn.hl7v2.model.v251.segment.MSA;
import ca.uhn.hl7v2.model.v251.segment.MSH;
import ca.uhn.hl7v2.parser.GenericParser;
import ca.uhn.hl7v2.parser.Parser;
import org.apache.struts.ehr.medical_records.model.ReplyMessage;

public class ParseReply{

	private ACK ack;
	
	public Object parseMessage(String message) throws Exception{
		Parser p = new GenericParser();
		Object data=null;
		 Message hapiMsg;
		 try {
		 // The parse method performs the actual parsing
			 hapiMsg = p.parse(message);
		 	 MSH mshSegment=(MSH)hapiMsg.get("MSH");
		 	 String msgType=mshSegment.getMessageType().getMessageCode().getValue();
			 String msgTrigger = mshSegment.getMessageType().getTriggerEvent().getValue();
			 data=identifyMessage(msgType, msgTrigger, hapiMsg);
		 }catch(HL7Exception e){
			 throw e;
		 }catch(IOException e){
			 throw e;
		 }catch(Exception e){
			 throw e;
		 }
		 return data;
	}
	
	private Object identifyMessage(String messageCode, String triggerEvent, Message hapiMsg)throws IOException, HL7Exception{
		Object object=null;
		 if(messageCode.equals("ADR") && triggerEvent.equals("A19")){
			ADR_A19 adr=(ADR_A19)hapiMsg;
			if(adr.getMSA().getAcknowledgmentCode().getValue()!=null){
				if((adr.getMSA().getAcknowledgmentCode().getValue()).equals("AA")){
					String list_of_beds=adr.getMSA().getTextMessage().getValue();
					object=list_of_beds;
				}
			}
			else{
				object=adr;
			}
		}else if(messageCode.equals("ACK")){
			this.ack=(ACK)hapiMsg;
			String value=ack.getMSA().getAcknowledgmentCode().getValue();
			if(value.equals("AA")){
				ReplyMessage message=new ReplyMessage();
				message.setMessage("Success!!");
				object=message;
			}
			else if(value.equals("AR")){
				ReplyMessage message=new ReplyMessage();
				message.setMessage(ack.getERR().getErrorCodeAndLocation(0).getCodeIdentifyingError().getAlternateText().getValue());
				object=message;
			}
			else if(value.equals("AE")){
				ReplyMessage message=new ReplyMessage();
				message.setMessage(ack.getERR().getErrorCodeAndLocation(0).getCodeIdentifyingError().getAlternateText().getValue());
				object=message;
			}
		}else{
			ReplyMessage message=new ReplyMessage();
			message.setMessage("Unexpected Reply from the back end");
			object=message;
		}
		return object;
	}

}
